package com.javabasic.algorithm.leetcode;

import cn.hutool.core.collection.CollUtil;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2024/1/12 20:10
 */
public class CountCommonWordsWithOneOccurrence {


    public static Stream<List<List<String>>> testData() {
        return Stream.of(
                CollUtil.newArrayList(CollUtil.newArrayList("a", "ab"),
                        CollUtil.newArrayList("a", "a", "a", "ab"))
        );
    }

    @ParameterizedTest
    @MethodSource("testData")
    public void testCountWords(List<List<String>> words) {
        countWords(words.get(0).toArray(new String[words.get(0).size()]), words.get(1).toArray(new String[words.get(1).size()]));
    }


    public int countWords(String[] words1, String[] words2) {
        int num;
        Map<String, Integer> strToCount1 = new HashMap<>(16);
        int len1 = words1.length;
        for (int i = 0; i < len1; i++) {
            num = strToCount1.getOrDefault(words1[i], 0);
            strToCount1.put(words1[i], ++num);
        }

        Map<String, Integer> strToCount2 = new HashMap<>(16);
        int len2 = words2.length;
        for (int i = 0; i < len2; i++) {
            num = strToCount2.getOrDefault(words2[i], 0);
            strToCount2.put(words2[i], ++num);
        }

        int len = len1 < len2 ? len1 : len2;
        String[] words = len1 < len2 ? words1 : words2;
        int result = 0;
        for (int i = 0; i < len; i++) {
            if (strToCount1.getOrDefault(words[i], 0) == 1 && strToCount2.getOrDefault(words[i], 0) == 1) {
                result++;
            }
        }
        return result;
    }
}
